package org.nicocube.airain.gwt.server;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.nicocube.airain.domain.server.data.ContainerProvider;
import org.nicocube.airain.domain.server.data.ContainerProviderImpl;
import org.nicocube.airain.domain.server.data.StorageProvider;
import org.nicocube.airain.utils.config.ConfigProvider;

public class StorageManager extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private static StorageProvider storageProvider;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		String f = config.getInitParameter("storage.file");
		
		ContainerProvider provider;
		try {
			provider = new ContainerProviderImpl(ConfigProvider.inst().provide(f));
		} catch (FileNotFoundException e) {
			throw new ServletException("",e);
		} catch (IOException e) {
			throw new ServletException("",e);
		}
		
		storageProvider = new StorageProvider(provider);
		
	}

	public static StorageProvider getStorageProvider() {
		if (storageProvider==null) loadDefaultStorageProvider();
		return storageProvider;
	}

	/**
	 * This method is for GWT browser test, because it do not load web.xml
	 */
	private static synchronized void loadDefaultStorageProvider() {
		if (storageProvider==null) {
			ContainerProvider provider;
			try {
				provider = new ContainerProviderImpl(ConfigProvider.inst().provide("./storage.properties"));
			} catch (FileNotFoundException e) {
				throw new IllegalStateException("While loading default StorageProvider:"+e.getMessage(),e);
			} catch (IOException e) {
				throw new IllegalStateException("While loading default StorageProvider:"+e.getMessage(),e);
			}
			storageProvider = new StorageProvider(provider);
		}
	}
	
}
